package com.ktjiaoyu.crm.controller;

import com.ktjiaoyu.crm.base.shiro.MyShiroRealm;
import com.ktjiaoyu.crm.pojo.Right;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.RoleService;
import com.ktjiaoyu.crm.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class IndexController {
    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //redis中的数据的前缀
    private String SHIRO_LOGIN_COUNT="shiro_login_count";//登录次数
    //登录页面
    @RequestMapping(value = "/login")
    public String login() {
        return "login";
    }
    //登录跳转
    @RequestMapping(value = "/doLogin")
    public String dologin(String usrName, String usrPassword,Model model, HttpServletRequest request,
                          HttpSession session){
/*        User user=userService.login(usrName,usrPassword);
        if(user!=null){
            request.getSession().setAttribute("loginUser",user);
            return "redirect:/main";
        }else{
            request.setAttribute("message","登录失败，用户名或密码错误！");
            return "login";
        }*/
        try{
//            usrPassword=userService.encryptPassword(usrPassword);//封装之前先进行加密
            UsernamePasswordToken token=new UsernamePasswordToken(usrName,usrPassword);
            Subject subject= SecurityUtils.getSubject();
            subject.login(token);//认证，登录
            //认证（登录成功），清空登录计数
            stringRedisTemplate.delete(SHIRO_LOGIN_COUNT+usrName);
            User user= (User) subject.getPrincipal();
            //获取权限
            Role role=user.getRole();//如果一对多关联不是立即加载，则需要通过用户获取角色
            List<Right> rights=roleService.findRightsByRole(role);

            role.getRights().addAll(rights);
            session.setAttribute("loginUser",user);
//            String id = session.getId();
//            Serializable id1 = subject.getSession().getId();
            //清空权限缓存
            RealmSecurityManager rsm= (RealmSecurityManager) SecurityUtils.getSecurityManager();
            MyShiroRealm realm= (MyShiroRealm) rsm.getRealms().iterator().next();
            realm.clearMyCachedAuthorizationInfo();
            return "redirect:/main";//建议重定向
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            model.addAttribute("message","用户名或密码错误,登录失败！");
            return "login";
        }catch (LockedAccountException e) {
            model.addAttribute("message","用户被禁用，登录失败！");
            return "login";
        }catch (AuthenticationException e) {
            model.addAttribute("message","认证异常，登录失败！");
            return "login";
        }

    }
    //主页面
    @RequestMapping(value = "/main")
    public String main(){
        return "main";
    }

    @RequestMapping(value = "/403")
    public String unauthorized(){
        return "403";
    }
}
